import { createApp } from "vue";
import Vant from "vant";
import mitt from "mitt";
import "vant/lib/index.css";
import router from "@/router";
import App from "@/App";
import store from "@/store";
import socket from "./socket";
import Indexdb from "@/utils/indexdb";
import { Toast } from "vant";

const app = createApp(App);
const db = new Indexdb("qq");
const state = store.state;

let timer = null;

app.$bus = mitt();

if (!localStorage.getItem("qq")) {
  timer = setInterval(() => {
    Toast("请等待第一次初始化后在操作");
  });
  db.createDatabase().then((e) => {
    db.createTable("chat_record")
      .then((e) => {
        Toast("初始化成功");
        clearInterval(timer);
      })
      .catch(() => {});
  });
} else {
  console.log("已创建");
  (async () => {
    let chats = (await db.selectAll("chat_record"))[0]?.nowChats;
    if (chats) {
      store.dispatch("notify/setNowChats", chats);
    }else{
      console.log("没有数据");
    }
  })();
}

socket.on("connect", () => {
  console.log("客户端链接成功", socket.id);
});

socket.on("connect", () => {
  console.log("客户端链接成功", socket.id);
});

router.beforeEach(async (to, from, next) => {
  const token = state.user.token;
  const userInfo = JSON.stringify(state.user.userInfo);
  if (
    (token === "" || userInfo === "{}") &&
    to.path !== "/login" &&
    to.path !== "/register"
  ) {
    return router.replace({
      path: "/login",
    });
  } else {
    if (token !== "" && userInfo !== "{}") {
      if (to.path === "/login") {
        router.replace({
          path: "/",
        });
      }
    }
  }
  next();
});

router.afterEach((to, from) => {
  document.title = to.meta.title ? to.meta.title : "消息";
});

app.config.globalProperties.$socket = socket;
app.$db = db;

app.use(Vant).use(store).use(router).mount("#app");
